//
//  PayAli.m
//  ProjectPublic
//
//  Created by ac-hu on 2018/7/12.
//  Copyright © 2018年 ac hu. All rights reserved.
//

#import "PayAli.h"

@interface PayAli()
@property(nonatomic,copy)NSString *appScheme;
@property(nonatomic,copy)succeedPay succeedBlock;
@property(nonatomic,copy)failPay faiBlock;
@end

@implementation PayAli

+(instancetype)share{
    static PayAli *pay;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (pay == nil) {
            pay = [[PayAli alloc]init];
            [pay configruation];
        }
    });
    return pay;
}

-(void)configruation{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Info" ofType:@"plist"];
    NSDictionary * dict = [[NSDictionary alloc] initWithContentsOfFile:path];
    NSArray * URLTypes = dict[@"CFBundleURLTypes"];
    
    for (NSDictionary * dic in URLTypes) {
        if ([[dic objectForKey:@"CFBundleURLName"] isEqualToString:@"alipay"]) {
            NSArray * URLSchemes= [dic objectForKey:@"CFBundleURLSchemes"];
            self.appScheme = URLSchemes.firstObject;
            break;
        }
    }
}

-(void)payOrder:(id)order succeed:(succeedPay)succeed fail:(failPay)fail{
    if (order == nil) {
        fail(@"参数为空");
        return;
    }
    self.succeedBlock = succeed;
    self.faiBlock = fail;
    __weak typeof(self) weekSelf = self;
    [[AlipaySDK defaultService] payOrder:order fromScheme:self.appScheme callback:^(NSDictionary *resultDic) {
        [weekSelf processResult:resultDic];
    }];
}

-(void)monitorResult:(NSURL *)url{
    if (![url.host isEqualToString:@"safepay"]) {
        return;
    }
    [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
        [self processResult:resultDic];
    }];
}

-(void)processResult:(NSDictionary *)resultDic{
    NSLog(@"reslut = %@",resultDic);
    //这里建议去服务器拉取
    NSInteger orderState = [[resultDic objectForKey:@"resultStatus"] integerValue];
    switch (orderState) {
        case 8000:
            if (self.faiBlock){
                self.faiBlock(@"订单正在处理中");
            }
            break;
            
        case 4000:
            if (self.faiBlock){
                self.faiBlock(@"订单支付失败");
            }
            break;
            
        case 6001:
            if (self.faiBlock) {
                self.faiBlock(@"订单取消");
            }
            break;
            
        case 6002:
            if (self.faiBlock) {
                self.faiBlock(@"网络连接出错");
            }
            break;
            
        default:
            if (self.succeedBlock) {
                self.succeedBlock(@"支付成功");
            }
            break;
    }
}

@end
